package com.markhsiu.MiniMQ.remote.transport.netty.handler;

import com.markhsiu.MiniMQ.client.CallBackCache;
import com.markhsiu.MiniMQ.client.CallBackor;
import com.markhsiu.MiniMQ.model.Message;
import com.markhsiu.MiniMQ.model.Result;
import com.markhsiu.MiniMQ.model.constant.MessageCmdEnum;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Mark Hsiu on 2017/2/8.
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter{

	private CallBackor callBackor;
	
	public NettyClientHandler(CallBackor callBackor) {
		this.callBackor = callBackor ;
	}
	
    //管道链路激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	 super.channelActive(ctx);
    }

    // 当服务器端返回应答消息时，channelRead方法被调用，Netty的ByteBuf中读取并打印应答消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        Result result =  CallBackCache.getCallBack(message.getMessageID());
        if(result != null){
        	result.setMessage(message);
            result.release();
        }
               
        if(callBackor != null){
        	result = new Result();
        	result.setMessage(message);
        	callBackor.print(result);
        	
        	Message response = new Message();
        	response.setMessageID(message.getMessageID());
        	response.setConsumerID(message.getConsumerID());
        	response.setCmd(MessageCmdEnum.SUCCESS);
        	response.setTimestamp(System.currentTimeMillis());
        	ctx.writeAndFlush(response);
 
        } 
    	
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 释放资源
        ctx.close();
    }
}
